﻿using System.Net.Http;
using System.Web.Http.Controllers;
using System.Linq;

namespace Inovout.Web.Http
{
    public class HttpControllerActionSelector : ApiControllerActionSelector
    {
        public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
        {
            //为兼容IE8,IE9不能发送DELETE和PUT，采用模拟的方式
            var httpmethodQuery = controllerContext.Request.GetQueryNameValuePairs().SingleOrDefault(
                q => q.Key.ToLower().Equals("@http-method"));
            if (!string.IsNullOrEmpty(httpmethodQuery.Value))
            {
                if (controllerContext.Request.Method == HttpMethod.Get && httpmethodQuery.Value.ToLower().Equals("delete"))
                {
                    controllerContext.Request.Method = HttpMethod.Delete;
                }
                if (controllerContext.Request.Method == HttpMethod.Post && httpmethodQuery.Value.ToLower().Equals("put"))
                {
                    controllerContext.Request.Method = HttpMethod.Put;
                }
            }
            foreach (var query in controllerContext.Request.GetQueryNameValuePairs())
            {
                if (query.Key.StartsWith("@"))
                {
                    controllerContext.Request.Headers.Add(query.Key.Substring(1, query.Key.Length - 1), query.Value);
                }
            }
            return base.SelectAction(controllerContext);
        }
    }
}
